package com.ineatconseil.yougo.pages.usertypes.view;

import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;

import com.ineatconseil.yougo.beans.ActionType;
import com.ineatconseil.yougo.beans.UserType;
import com.ineatconseil.yougo.dto.UserTypeDto;
import com.ineatconseil.yougo.exceptions.RestServiceException;
import com.ineatconseil.yougo.pages.AbstractPage;
import com.ineatconseil.yougo.pages.usertypes.list.UserTypesList;
import com.ineatconseil.yougo.services.rest.RestPath;

public class UserTypeView extends AbstractPage {

	@Property
	private UserType userType;

	@Property
	@Persist(PersistenceConstants.SESSION)
	private long userTypeId;

	@Component(id = "formUserType")
	private BeanEditForm _form;

	@InjectPage
	private UserTypesList userTypesList;

	/**
	 * Load action.
	 */
	@Log
	void onActivate(long userTypeId) {

		try {

			if (!isEmptyParameter(String.valueOf(userTypeId))) {

				userType =
						this.getMapper().map(
								this.getRestServiceInvoker().call(
										RestPath.getSimplePath(RestPath.PATH_USER_TYPES, String.valueOf(userTypeId)),
										UserTypeDto.class), UserType.class);

				this.userTypeId = userTypeId;
			} else {
				userType = new UserType();
				this.userTypeId = 0;
			}

		} catch (RestServiceException e) {
			_form.recordError(getRESTErrorMessage(e.getStatus()));
		}

	}

	/**
	 * Submit action.
	 */
	@Log
	Object onSuccess() {

		try {

			if (this.userTypeId != 0) {

				// Update
				this.userType.setId(this.userTypeId);
				this.getRestServiceInvoker().update(
						RestPath.getSimplePath(RestPath.PATH_USER_TYPES, String.valueOf(userTypeId)),
						getMapper().map(userType, UserTypeDto.class), UserTypeDto.class);

				userTypesList.setActionMessageOk("usertype", ActionType.UPDATE);

			} else {

				// Create
				this.userType.setId(null);
				this.getRestServiceInvoker().save(RestPath.getSimplePath(RestPath.PATH_USER_TYPES, ""),
						getMapper().map(userType, UserTypeDto.class), UserTypeDto.class);

				userTypesList.setActionMessageOk("usertype", ActionType.CREATE);

			}
			return userTypesList;

		} catch (RestServiceException e) {
			_form.recordError(getRESTErrorMessage(e.getStatus()));
			return null;
		}

	}
}
